package com.baseframe.match.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baseframe.auth.utils.AuthUtil;
import com.baseframe.match.entity.SnsMatch;
import com.baseframe.match.entity.SnsMatchUser;
import com.baseframe.match.entity.request.SnsMatchRequest;
import com.baseframe.match.entity.vo.SnsMatchVO;
import com.baseframe.match.service.SnsMatchService;
import com.baseframe.match.service.SnsMatchUserService;
import com.baseframe.mybatis.utils.PageInfo;
import com.baseframe.tool.result.R;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/front/match")
@AllArgsConstructor
public class FrontBaseMatchController {

    private SnsMatchService snsMatchService;
    private SnsMatchUserService snsMatchUserService;


    /**
     * 竞赛报名
     * @param request 请求
     * @return R
     */
    @PostMapping("/enroll")
    public R<Object> matchEnroll(@RequestBody SnsMatchRequest request){

        if (request.getId()==null){
            return R.fail("缺少必要请求参数~");
        }

        SnsMatchUser snsMatchUser = snsMatchUserService.getOne(new LambdaQueryWrapper<SnsMatchUser>().eq(SnsMatchUser::getMatchId, request.getId()).eq(SnsMatchUser::getUserId, AuthUtil.getUserId()));

        if(snsMatchUser!=null){
            return R.fail("您已经报名过了~");
        }

        snsMatchUser = new SnsMatchUser();
        snsMatchUser.setMatchId(request.getId());
        snsMatchUser.setUserId(AuthUtil.getUserId());
        snsMatchUser.setEnrollTime(new Date());

        return snsMatchUserService.save(snsMatchUser)?R.success():R.fail();
    }


    /**
     * 获取最新的竞赛列表
     * @return 统一返回对象
     */
    @GetMapping("/new/list")
    public R<List<SnsMatchVO>> getMatchNewList(){

        return R.data(snsMatchService.getNewList());
    }

    /**
     * 前台竞赛分页列表
     * @param pageInfo 分页信息
     * @param request 查询信息
     * @return 统一响应信息
     */
    @GetMapping("/page")
    public R<Page<SnsMatchVO>> getMatchPageList(PageInfo pageInfo, SnsMatchRequest request){


        return R.data(snsMatchService.matchPageList2Front(pageInfo,request));
    }


    /**
     * 通过id获取竞赛详情
     * @param request 请求参数
     * @return 统一返回类型
     */
    @GetMapping("/details")
    public R<Object> getMatchDetails(SnsMatchRequest request){

        if (request.getId() == null){
            return R.fail("缺少必要请求参数");
        }

        return R.data(snsMatchService.getDetailsById(request.getId()));
    }





}
